/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//==============================================================================websocket begin
//初始化所需 用户信息
$websocketInitData = ajaxSynchroRequest('/api/index/websocket-init');
//console.log($websocketInitData);
//获取用户登录的服务器信息
var music=document.getElementById("mymusic");
var server = "";
var usercode = "";
var userid = "";
var isconnected = 0;
if($websocketInitData.success == 1){
    console.log($websocketInitData);
    server = $websocketInitData.data.server;
    usercode = $websocketInitData.data.usercode;
    userid = $websocketInitData.data.userid;
    username = $websocketInitData.data.username;
    headimg = $websocketInitData.data.headimg;
}else{
    var server = "";
    var usercode = "";
}
//console.log(server);
var ws;
if(server != "" && usercode != ""){
    var ws = new WebSocket("ws://"+server);
    //【用于指定连接成功后的回调函数】
    ws.onopen = function (evt) {
        console.log("Connection open ...");
        var json = {"sockettype":1,"usercode":usercode,"server":server,"msg_type":0}; //创建对象；
        var jsonStr = JSON.stringify(json);       //转为JSON字符串
        ws.send(jsonStr);       //首次发送 用户与服务器交互的信息
        isconnected = 1;
    };
    //[【于指定连接关闭后的回调函数。】
    ws.onclose = function (evt) {
        console.log("Connection closed.");
        isconnected = 0;
    };
    ws.onmessage = function (event) {
        console.log("index page Received Message: " + event.data);
        var msg = JSON.parse(event.data);//json字符串转化为对象
        dealmsg(msg);
    };
    //webSocket.onerror 用于指定报错时的回调函数
    ws.onerror = function (event) {
        //window.location.reload();
        console.log(event);
        console.log("event error");
    };

    //每隔5秒检测长连接
    setInterval(function() {
        if(ws.readyState === 1){
            var json = {"1":1}; //创建对象；
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            ws.send(jsonStr);
        }else if(ws.readyState === 3){
            ws = new WebSocket("ws://"+server);
            //【用于指定连接成功后的回调函数】
            ws.onopen = function (evt) {
                console.log("Connection open ...");
                var json = {"sockettype":1,"usercode":usercode,"server":server,"msg_type":0}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串
                ws.send(jsonStr);       //首次发送 用户与服务器交互的信息
                isconnected = 1;
            };

            //[【于指定连接关闭后的回调函数。】
            ws.onclose = function (evt) {
                console.log("Connection closed.");
                isconnected = 0;
            };
            ws.onmessage = function (event) {
                //console.log("index page Received Message: " + event.data);
                var msg = JSON.parse(event.data);//json字符串转化为对象
                dealmsg(msg);
            };
        }
    }, 30000);
}
function dealmsg(msg){
    console.log(msg);
//    console.log("userid is " + userid);
    var msgnum = "";
    var friend_id = $("#friend_id").val();
    if(msg.touserid == userid && friend_id == msg.fromuserid){
        music.play();
        //好友消息
        if(msg.msgcate === 3){
            //"sockettype":3,"msgcate":3,"msgtype":"text","content":"vvvvv","chat_id":"4","fromuser":"admin","fromuserid":1,"fromheadimg":"/userhead\\1\\1573814307.png","touserid":"10"
            var youhtml = '<div class="chat-msg" id="msg'+msg.msgid+'"><div class="user-head-you"><img class="head-img" src="'+msg.fromheadimg+'" /></div><div class="msg-content-you"><div class="chat-content-you">'+msg.content+'</div></div></div>'
            
            $("#chat-msg-you-and-me").append(youhtml);

            window.scroll({top:10000000,left:0,behavior:'smooth'});
            //设置为已读消息
            
            $params = JSON.stringify({'chatid':msg.chat_id});
            $set_read_back = ajaxSynchroRequest("/api/friends/set-read",$params);
        }
    }
}
//==============================================================================websocket end
$(document).ready(function(){
    window.scroll({top:10000000,left:0,behavior:'smooth'});
    $("#input-focus-background").hide();
    $("#content-edit").focus(function(){
        console.log("获得焦点");
//        $("#chat-editor-outter").css("bottom",'250px');
        $("#input-focus-background").show();
        window.scroll({top:10000000,left:0,behavior:'smooth'});
    });
    $("#chat-msg-you-and-me").on('click',function(){
//        $("#chat-editor-outter").css("bottom",'0');
        $("#input-focus-background").hide();
    });
    
    $("#msg-submit").on('click',function(){
        var content = $("#content-edit").val();
        var chatid = $(this).attr('data-chatid');
        var friend_id = $(this).attr('data-friendid');
        var friend_name = $(this).attr('data-friendname');
        if(content == ""){
            layer.open({
                content: '消息不能为空！',
                skin: 'msg',
                time: 3 //3秒后自动关闭
            });
            return false;
        }
        $params = JSON.stringify({'chatid':chatid,'sender':username,'senderid':userid,'sendee':friend_name,'sendeeid':friend_id,'content':content});
        $newmsg_back = ajaxSynchroRequest("/api/friends/newchatmsg",$params);
        var msgid = $newmsg_back.msg_id;
        
        var json = {'sockettype':3,'msgcate':3,'msgtype':'text','content':content,'chat_id':chatid,'msgid':msgid,'fromuser':username,'fromuserid':userid,'fromheadimg':headimg,'touserid':friend_id}; //创建对象；
        var jsonStr = JSON.stringify(json);       //转为JSON字符串
        ws.send(jsonStr);
        
        var myhtml = '<div class="chat-msg" id="msg'+msgid+'"><div class="user-head-me"><img class="head-img" src="'+headimg+'" /></div><div class="msg-content-me"><div class="chat-content-me">'+content+'</div></div></div>';
        $("#chat-msg-you-and-me").append(myhtml);
        $("#content-edit").val("");
        $("#chat-editor-outter").css("bottom",'0');
        $("#input-focus-background").hide();
        window.scroll({top:10000000,left:0,behavior:'smooth'});
    });
    
    $("#more-msg").on('click',function(){
        var chatid = $(this).attr('data-chatid');
        var friendid = $(this).attr('data-friendid');
        var latest_first = $("#latest-first").val();
        $params = JSON.stringify({'chatid':chatid,'latest_first':latest_first});
        $moremsg_back = ajaxSynchroRequest("/api/friends/get-historymsg",$params);
        if($moremsg_back.success == 1){
            if($moremsg_back.data.length > 0){
                var friend_headimg = $("#friend_headimg").val();
                var last = $moremsg_back.data.length-1;
                var more_msg_html = '';
                for(i=last;i>=0;i--){
                    if(friendid == $moremsg_back.data[i].senderid){
                        more_msg_html += '<div class="chat-msg" id="msg'+$moremsg_back.data[i].id+'"><div class="user-head-you"><img class="head-img" src="'+friend_headimg+'" /></div><div class="msg-content-you"><div class="chat-content-you">'+$moremsg_back.data[i].content+'</div></div></div>';
                    }else{
                        more_msg_html += '<div class="chat-msg" id="msg'+$moremsg_back.data[i].id+'"><div class="user-head-me"><img class="head-img" src="'+headimg+'" /></div><div class="msg-content-me"><div class="chat-content-me">'+$moremsg_back.data[i].content+'</div></div></div>';
                    }
                }
                $("#latest-first").val($moremsg_back.data[last].id);
                $("#chat-msg-you-and-me").prepend(more_msg_html);
            }else{
                $("#more-msg").hide();
            }
            
        }
    });
});

